import { reactive, inject, provide } from 'vue';
import { ConsoleLogger } from '@/utils/debug-log';
import { Prepare } from '../types/prepare';
import { getPrepareLessons } from '../api/editor/index';
import { AnswersTestID, TeacherID, WorkID } from '../types';

const console = new ConsoleLogger('备课资源');
const usePrepareSymbol = Symbol('usePrepare store');

export interface IPrepareState {
  // teacherId:TeacherID;
  workerId: WorkID;
  preparePromise: Record<string, any>;
  prepare?: Prepare; //
  prepareImgList: Array<{ id: AnswersTestID; url: string }>; //
}

export interface IUsePrepareStoreFn {
  (): IUsePrepareStore;
  __CurrentStore?: IUsePrepareStore;
}

export interface IUsePrepareStore {
  state: IPrepareState;
  gainPrepare: (workerId: WorkID) => Promise<any>;
  setPrepareImgList: (id: AnswersTestID, url: string) => void;
  getPrepareImgList: (id: AnswersTestID) => string;
  init: (workerId: WorkID) => void;
}

/**
 *  * usePrepareStore 用户hooks.
 * @function
 * @params {IPrepareState} userState - 用户信息.
 * @returns store extend IUsePrepareStore
 */
export const usePrepareProvide: () => IUsePrepareStore = () => {
  const state = reactive<IPrepareState>({
    // teacherId,
    workerId: 0,
    preparePromise: {},
    prepareImgList: []
  });
  const setPrepareImgList = (id: AnswersTestID, url: string) => {
    const list = state.prepareImgList.filter((n) => n.id === id);
    if (list.length > 0) {
      list[0].url = url;
    } else {
      state.prepareImgList.push({ id, url });
    }
  };
  const getPrepareImgList = (id: AnswersTestID) => {
    const list = state.prepareImgList.filter((n) => n.id === id);
    if (list.length > 0) {
      return list[0].url;
    }
    return '';
  };
  /**
   * 获取备课信息
   */
  const gainPrepare = async (workerId: WorkID) => {
    const res = await getPrepareLessons(workerId);
    /**失败与成功都需要赋值 */
    state.prepare = res.data;
    state.prepareImgList = [];
  };
  /**
   * 初始化备课信息
   */
  const init = async (workerId: WorkID) => {
    await gainPrepare(workerId); //获取备课资源
  };

  const store: IUsePrepareStore = {
    state,
    init,
    setPrepareImgList,
    getPrepareImgList,
    gainPrepare
  };

  provide(usePrepareSymbol, { ...store });
  return store;
};

/**
 *  * usePrepareStore 用户hooks.
 * @function
 * @returns store extend IUsePrepareStore
 */
export const usePrepareStore: IUsePrepareStoreFn = () => {
  const store: IUsePrepareStore = inject(usePrepareSymbol) as IUsePrepareStore;
  return store;
};
